<?php

namespace app\common\service\order\pipeline\coupon;

use api\channel\jutuike\AroundUnion;
use app\common\service\around\JtkAroundService;
use app\model\CouponOrder;
use app\model\JtkGoods;
use think\Exception;

class JutuikeAroundBeforeValidate
{

    // 订单是否需要脚本跑 10分钟失效
    public static function handle(CouponOrder $couponOrder, $next) {

        $params = $couponOrder->params;
        $serv_type = $params['serv_type'] ?? '';

        if ($serv_type != PRODUCT_AROUND_SHOP_SERV) {
            return $next($couponOrder);
        }

        self::checkRules($couponOrder);

        self::checkGoods($couponOrder);

        // 先生成订单编号
        $couponOrder->order_id = self::getOrderId();

        $couponOrder->serv_type = $serv_type;

        $next($couponOrder);
    }

    /**
     * 效验规则
     * @return void
     * @throws Exception
     */
    public static function checkRules(CouponOrder &$couponOrder) {
        $params = $couponOrder->params;

        $rules = [
            'serv_type' => 'require',
            'productId' => 'require',
            'itemId' => 'require',
            'locationId' => 'require|number',
            'itemSalePrice' => 'require',  // 套餐单价 单位元
            'quantity' => 'require|regex:^[1-9]\d*$',
            'customerName' => 'require',
            'customerPhoneNumber' => 'require|mobile',
        ];

        $message = [
            'serv_type.require' => '产品类型不能为空',
            'productId.require' => '产品编号id不能为空',
            'itemId.require' => '套餐编号id不能为空',
            'itemSalePrice.require' => '套餐单价不能为空',
            'locationId.require' => '站点编号不能为空',
            'quantity.require' => '购买数量不能为空',
            'quantity.regex' => '购买数量格式有误',
            'customerName.require' => '客户姓名不能为空',
            'customerPhoneNumber.require' => '客户电话不能为空',
            'customerPhoneNumber.mobile' => '客户电话格式有误',
        ];
        $msg = dmjValidate($rules, $message, $params);

        if ($msg) {
            throw new Exception($msg);
        }
    }

    /**
     * 效验商品
     * @param CouponOrder $couponOrder
     * @return void
     * @throws Exception
     */
    public static function checkGoods(CouponOrder &$couponOrder) {
        $params = $couponOrder->params;
        $buyQuantity = $params['quantity']; // 购买数量

        $productId = $params['productId'];
        $itemId = $params['itemId'];
        $productParams = [
            'itemId' => $itemId,
            'productId' => $productId,
            'locationId' => $params['locationId'],
        ];
        $aroundUnion = new AroundUnion();
        $res = $aroundUnion->queryProductByCondition($productParams);
        $code = $res['code'] ?? JtkAroundService::CODE_FAIL;
        if ($code != JtkAroundService::CODE_SUCCESS) {
            $msg = $res['msg'] ?? '商品信息获取异常，请联系管理员';
            throw new Exception($msg);
        }
        $jutuikeGoodsInfo = $res['data'] ?? [];
        if (empty($jutuikeGoodsInfo)) {
            throw new Exception('购买的商品不存在，请联系管理员');
        }

        // 聚推客的商品信息
        $couponOrder->params['jutuikeGoodsInfo'] = $jutuikeGoodsInfo;

        $items = $jutuikeGoodsInfo['items'] ?? [];
        if (empty($items)) {
            throw new Exception('购买的商品套餐不存在，请联系管理员');
        }

        $singleMin = $jutuikeGoodsInfo['singleMin'] ?? '';
        $singleMax = $jutuikeGoodsInfo['singleMax'] ?? '';

        if (isset($jutuikeGoodsInfo['isSoldOut']) && $jutuikeGoodsInfo['isSoldOut'] == 1) {
            throw new Exception('商品已售罄');
        }

        if ($singleMin && $singleMax && ($buyQuantity < $singleMin || $buyQuantity > $singleMax) ) {
            throw new Exception('购买的商品数量有误，请核查');
        }

        $itemsCur = Collect($items)->where('id', $itemId);
        if (empty($itemsCur)) { // 购买商品套餐和当前商品套餐不一致
            throw new Exception('购买商品套餐有误，请核实');
        }

        $itemInfo = $itemsCur->first();
        $itemSalePriceFen = yuan2fen($params['itemSalePrice']); //  前端传过来的是元
        if ($itemSalePriceFen != $itemInfo['salePrice']) { // 传入商品套餐的单价和聚推客的不一样
            throw new Exception('购买商品套餐单价有误，请核实');
        }

        $itemSingleMax = $itemInfo['singleMax'];
        if ($buyQuantity > $itemSingleMax) {
            throw new Exception('购买商品套餐数量已超出单次最大数量，请核实');
        }

        // 本地存储的商品ID
//        $jtkGoods = JtkGoods::findModel($productId);
//        $couponOrder->params['localJtkGoodsId'] = $jtkGoods->id ?? 0;
    }

    /**
     * 订单编号
     * @return string
     */
    public static function getOrderId()
    {
        return time() . rand(100000, 999999);
    }

}